import { Injectable } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import { getRandomChineseCharacterFromLibrary } from '../utils'
import { UtilityService } from './utility.service';
import {v4 as uuidv4} from 'uuid';

@Injectable()
export class CaptchaService {
    constructor(private readonly utilityService: UtilityService) { }
    hasDuplicateChars(str) {
        return new Set(str).size !== str.length;
    }
    generateChineseCaptcha(obj:any): any {
        // 生成4个随机中文字符
        // const text = getRandomChineseCharacterFromLibrary();
        // const text = this.utilityService.generateRandomStringIncomplete(4);
        if(obj.size < 4){
            obj.size = 4;
        }
        let order = 4;
        if(obj.order >= 3){
            if(obj.order>obj.size){
                return;
            }
            order = obj.order;
        }
        let captcha;
        // 配置验证码参数
        do {
            if(obj.lang === 'cn'){
                svgCaptcha.loadFont('./keaishaonuti.otf');
                captcha = svgCaptcha.create({
                    width: 360,  // 设置验证码的宽度
                    height: 50,  // 设置验证码的高度
                    size: 6,
                    noise: 4,
                    color: true,
                    background: '#f0f0f0',
                    ignoreChars: '0oO1ilI',
                    fontSize: 20,
                    charPreset: getRandomChineseCharacterFromLibrary(50),
                    ...obj,
                });
            }else{
                captcha = svgCaptcha.create({
                    width: 360,  // 设置验证码的宽度
                    height: 50,  // 设置验证码的高度
                    size: 6,
                    noise: 4,
                    color: true,
                    background: '#f0f0f0',
                    ignoreChars: '0oO1ilI',
                    // charPreset: '1+-*/23456789', // 指定字符集为 1+-*/23456789
                    ...obj,
                });
            }
        } while (this.hasDuplicateChars(captcha.text))
        return {
            id: uuidv4(),
            data: captcha.data,
            order: captcha.text.split('').splice(1,order).sort(() => Math.random() - 0.5),
            text: captcha.text.split('') // 返回字符数组用于坐标记录
        };
    }
    generateMathCaptcha(): any {
        // 配置验证码参数
        let captcha = svgCaptcha.createMathExpr({
            width: 100,
            height: 50,
            noise: 4,
            color: true,
            background: '#f0f0f0',
            mathMin: 1, // 数学表达式可以是的最小值
            mathMax: 9, // 数学表达式可以是的最大值
            mathOperator: '+-' // 使用的运算符，可以是 '+', '-', 或 '+-'（随机 '+' 或 '-'
        });
        return {
            id: uuidv4(),
            data: captcha.data,
            text: captcha.text
        };
    }
}